/**
 * 
 */
package com.itboye.mengwu.app;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap.Config;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.itboye.core.server.ByService;
import com.itboye.core.utils.DebugLog;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.ui.mymeng.MegActivity;
import com.itboye.mengwu.app.ui.mymeng.MyOrderActivity;
import com.itboye.mengwu.app.ui.mymeng.personsettings.ActivitySiXinXiangQing;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

/**
 * @author hebidu
 * 
 */
public class MainApplication extends Application {

	public static Context context;

	private static RequestQueue queue;

	private static MainApplication getInstance;

	public static MainApplication getGetInstance() {
		return getInstance;
	}

	JSONObject jsonObject;

	protected int type;

	protected String uid;

	protected String nickName;

	public void initImageLoader() {
		long maxMamory = Runtime.getRuntime().maxMemory();// 应用程序程序运行时所使用最大内存数
		maxMamory = (long) (maxMamory * 0.7);
		int v = Runtime.getRuntime().availableProcessors();
		int availableProcessors = v < 4 ? 3 : v - 1;

		// System.out.println("maxMamory : " + maxMamory +
		// "  availableProcessors: " + availableProcessors);

		// DebugToast.show("maxMamory : " + (maxMamory/1024.0f/1024 )+
		// "  availableProcessors: " + availableProcessors, 1);

		DisplayImageOptions options = new DisplayImageOptions.Builder()
				// 设置图片下载期间显示的图片
				.showImageOnLoading(R.drawable.logo2)
				.showImageForEmptyUri(R.drawable.logo2)// 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.logo2) // 设置图片加载或解码过程中发生错误显示的图片
				.cacheInMemory(true)// 设置下载的图片是否缓存在内存中
				.cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
				.bitmapConfig(Config.RGB_565)
				// .displayer(new RoundedBitmapDisplayer(20))// 设置成圆角图片
				.build(); // 创建配置过得DisplayImageOption对象 

		// File cacheDir = StorageUtils.getOwnCacheDirectory(App.ctx,
		// "sunsun/Cache");
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getInstance)
				.memoryCacheExtraOptions(480, 800)
				// max width, max
				// height，即保存的每个缓存文件的最大长宽
				// .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75,
				// null) // Can slow ImageLoader, use it carefully (Better don't
				// use it)/设置缓存的详细信息，最好不要设置这个
				.threadPoolSize(availableProcessors)
				// 线程池内加载的数量
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 *
				// 1024)) // You can pass your own memory cache
				// implementation/你可以通过自己的内存缓存实现
				// .memoryCache(new WeakMemoryCache())

				.memoryCacheSize((int) maxMamory)
				// .memoryCacheSize(15 * 1024 * 1024)

				.diskCacheSize(80 * 1024 * 1024)
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())// 将保存的时候的URI名称用MD5
																		// 加密

				.tasksProcessingOrder(QueueProcessingType.LIFO) // 后进先出
				// .diskCacheFileCount(100) //缓存的文件数量
				// .diskCache(new UnlimitedDiscCache(cacheDir))//自定义缓存路径
				// .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
				.defaultDisplayImageOptions(options)
				// .imageDownloader(new BaseImageDownloader(App.ctx, 5 * 1000,
				// 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间
				// .imageDownloader(new DownloadImageFromNetWork(App.ctx, 5 *
				// 1000, 30 * 1000)).writeDebugLogs() // Remove
				// for
				// release
				// app
				.build();// 开始构建
		// Initialize ImageLoader with configuration.

		com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(
				config);// 全局初始化此配置

	}

	public static void setGetInstance(MainApplication getInstance) {
		MainApplication.getInstance = getInstance;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		getInstance = this;
		context = getApplicationContext();
		initImageLoader();
		Intent intent = new Intent(getApplicationContext(), ByService.class);
		// intent.putExtra("msg", "asdsdas");
		startService(intent);
		queue = Volley.newRequestQueue(context);
		initUMengPush();
	}

	private void initUMengPush() {

		PushAgent mPushAgent = PushAgent.getInstance(this);
		mPushAgent.setDebugMode(true);
		System.out.println("" + "zhixing1");
		UmengMessageHandler messageHandler = new UmengMessageHandler() {
			/**
			 * 参考集成文档的1.6.3 http://dev.umeng.com/push/android/integration#1_6_3
			 * */
			@Override
			public void dealWithCustomMessage(final Context context,
					final UMessage msg) {
				super.dealWithCustomMessage(context, msg);
				System.out.println("dealWithCustomMessage is In ui thread? "
						+ (Looper.getMainLooper() == Looper.myLooper()));
				new Handler().post(new Runnable() {

					@Override
					public void run() {
						System.out.println("" + "zhixing2");
						// TODO Auto-generated method stub
						// 对自定义消息的处理方式，点击或者忽略
						boolean isClickOrDismissed = true;
						if (isClickOrDismissed) {
							System.out.println("msg+" + msg);
							// 自定义消息的点击统计
							UTrack.getInstance(getApplicationContext())
									.trackMsgClick(msg);
						} else {
							System.out.println("" + "zhixing3");
							// 自定义消息的忽略统计
							UTrack.getInstance(getApplicationContext())
									.trackMsgDismissed(msg);
						}
						Toast.makeText(context, msg.custom, Toast.LENGTH_LONG)
								.show();
					}
				});
			}

			@Override
			public void dealWithNotificationMessage(Context arg0, UMessage arg1) {
				// TODO Auto-generated method stub
				super.dealWithNotificationMessage(arg0, arg1);
				System.out.println("执行了sssssssss2122");
				if (arg1.activity.equals("call_message")) {// 更新私信及私信列表界面
					Intent intent = new Intent("privatemsg");
					sendBroadcast(intent);

				}
				Intent intent2 = new Intent("change_img");
				sendBroadcast(intent2);
				System.out.println(">>>这是推送消息" + arg1.getRaw() + ":"
						+ arg1.extra.get("type"));
			}

			/**
			 * 参考集成文档的1.6.4 http://dev.umeng.com/push/android/integration#1_6_4
			 * */
			@Override
			public Notification getNotification(Context context, UMessage msg) {
				System.out.println("执行了sssssssss" + msg.builder_id);
				switch (msg.builder_id) {
				case 1:
					Toast.makeText(MainApplication.context, "zhixing4", 0)
							.show();
					System.out.println("执行了sssssssss");
					NotificationCompat.Builder builder = new NotificationCompat.Builder(
							context);
					RemoteViews myNotificationView = new RemoteViews(
							context.getPackageName(),
							R.layout.notification_view);
					myNotificationView.setTextViewText(R.id.notification_title,
							msg.title);
					myNotificationView.setTextViewText(R.id.notification_text,
							msg.text);
					myNotificationView.setImageViewBitmap(
							R.id.notification_large_icon,
							getLargeIcon(context, msg));
					myNotificationView.setImageViewResource(
							R.id.notification_small_icon,
							getSmallIconId(context, msg));
					builder.setContent(myNotificationView)
							.setContentTitle(msg.title)
							.setSmallIcon(getSmallIconId(context, msg))
							.setContentText(msg.text).setTicker(msg.ticker)
							.setAutoCancel(true);
					Notification mNotification = builder.build();
					// 由于Android
					// v4包的bug，在2.3及以下系统，Builder创建出来的Notification，并没有设置RemoteView，故需要添加此代码
					mNotification.contentView = myNotificationView;
					return mNotification;
					// case 2:
					// NotificationCompat.Builder builder = new
					// NotificationCompat.Builder(context);
					// RemoteViews myNotificationView = new
					// RemoteViews(context.getPackageName(),
					// R.layout.notification_view);
					// myNotificationView.setTextViewText(R.id.notification_title,
					// msg.title);
					// myNotificationView.setTextViewText(R.id.notification_text,
					// msg.text);
					// myNotificationView.setImageViewBitmap(R.id.notification_large_icon,
					// getLargeIcon(context, msg));
					// myNotificationView.setImageViewResource(R.id.notification_small_icon,
					// getSmallIconId(context, msg));
					// builder.setContent(myNotificationView)
					// .setContentTitle(msg.title)
					// .setSmallIcon(getSmallIconId(context, msg))
					// .setContentText(msg.text)
					// .setTicker(msg.ticker)
					// .setAutoCancel(true);
					// Notification mNotification = builder.build();
					// //由于Android
					// v4包的bug，在2.3及以下系统，Builder创建出来的Notification，并没有设置RemoteView，故需要添加此代码
					// mNotification.contentView = myNotificationView;
					// return mNotification;
					// case 3:
					//
				default:
					// 默认为0，若填写的builder_id并不存在，也使用默认。
					return super.getNotification(context, msg);
				}
			}

		};
		mPushAgent.setMessageHandler(messageHandler);

		/**
		 * // 创建一个NotificationManager的引用 NotificationManager notificationManager
		 * = (NotificationManager)
		 * this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
		 * 
		 * // 定义Notification的各种属性 Notification notification =new
		 * Notification(R.drawable.icon, "测试", System.currentTimeMillis());
		 * //FLAG_AUTO_CANCEL 该通知能被状态栏的清除按钮给清除掉 //FLAG_NO_CLEAR
		 * 该通知不能被状态栏的清除按钮给清除掉 //FLAG_ONGOING_EVENT 通知放置在正在运行 //FLAG_INSISTENT
		 * 是否一直进行，比如音乐一直播放，知道用户响应 notification.flags |=
		 * Notification.FLAG_ONGOING_EVENT; // 将此通知放到通知栏的"Ongoing"即"正在运行"组中
		 * notification.flags |= Notification.FLAG_NO_CLEAR; //
		 * 表明在点击了通知栏中的"清除通知"后，此通知不清除，经常与FLAG_ONGOING_EVENT一起使用
		 * notification.flags |= Notification.FLAG_SHOW_LIGHTS; //DEFAULT_ALL
		 * 使用所有默认值，比如声音，震动，闪屏等等 //DEFAULT_LIGHTS 使用默认闪光提示 //DEFAULT_SOUNDS
		 * 使用默认提示声音 //DEFAULT_VIBRATE 使用默认手机震动，需加上<uses-permission
		 * android:name="android.permission.VIBRATE" />权限 notification.defaults
		 * = Notification.DEFAULT_LIGHTS; //叠加效果常量
		 * //notification.defaults=Notification
		 * .DEFAULT_LIGHTS|Notification.DEFAULT_SOUND; notification.ledARGB =
		 * Color.BLUE; notification.ledOnMS =5000; //闪光时间，毫秒
		 * 
		 * // 设置通知的事件消息 CharSequence contentTitle ="标题"; // 通知栏标题 CharSequence
		 * contentText ="内容"; // 通知栏内容
		 * 
		 * //如果需要跳转到指定的Activity，则需要设置PendingIntent
		 * 
		 * Intent notificationIntent =new Intent(A.this, B.class); //
		 * 点击该通知后要跳转的Activity
		 * 
		 * notificationIntent.putExtra("date","需要传递的参数");
		 * 
		 * // FLAG_UPDATE_CURRENT
		 * 更新数据，如果有多个PendingIntent，且requestCode相同，则会替换为最新extra数据
		 * //如果需要通过不同的extra数据，进行处理，就需要requestCode不相同 int requestCode = new
		 * Random().nextInt(); PendingIntent contentItent =
		 * PendingIntent.getActivity(this, requestCode, notificationIntent,
		 * PendingIntent.FLAG_UPDATE_CURRENT);
		 * 
		 * 
		 * 
		 * notification.setLatestEventInfo(this, contentTitle, contentText,
		 * contentItent);
		 * 
		 * // 把Notification传递给NotificationManager notificationManager.notify(0,
		 * notification);
		 */

		/**
		 * 该Handler是在BroadcastReceiver中被调用，故
		 * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK 参考集成文档的1.6.2
		 * http://dev.umeng.com/push/android/integration#1_6_2
		 * */

		UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
			@Override
			public void dealWithCustomAction(Context context, UMessage msg) {
				super.dealWithCustomAction(context, msg);
				Toast.makeText(MainApplication.context, "执行中国", 0).show();
			}

			@Override
			public void openActivity(Context arg0, UMessage msg) {
				// TODO Auto-generated method stub
				// super.openActivity(arg0, msg);
				DebugLog.v("bytag", msg.activity);
				if (msg.activity.equals("bbs_message")) {
					try {
						jsonObject = msg.getRaw().getJSONObject("extra");
						// jsonObject = jsonObject.getJSONObject("after_open");
						type = jsonObject.getInt("type");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					// Intent intent = new Intent(MainApplication.context,
					// .class);
					// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					// if (type == 0) {
					// SPUtils.put(App.ctx, null, SPContants.IS_READ_ONE,
					// false);
					// intent.putExtra("current", 3);
					// } else if (type == 1) {
					// SPUtils.put(App.ctx, null, SPContants.IS_READ_TWO,
					// false);
					// intent.putExtra("current", 4);
					// }
					// startActivity(intent);
				} else if (msg.activity.equals("order_message")) {
					// try {
					// jsonObject = msg.getRaw().getJSONObject("extra");
					// jsonObject = jsonObject.getJSONObject("after_open");
					// order_code = jsonObject.getString("order_code");
					// } catch (JSONException e) {
					// // TODO Auto-generated catch block
					// e.printStackTrace();
					// }
					Intent intent = new Intent(getApplicationContext(),
							MyOrderActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					// String url =
					// "http://sunsun.itboye.com/index.php/Webview/Express/viewOrder?order_code="
					// + order_code;
					// System.out
					// .println("model.getExtra().getafterOpen().getOrderCode()"
					// + order_code);
					startActivity(intent);

				} else if (msg.activity.equals("system_message")) {
					// try {
					// jsonObject = msg.getRaw().getJSONObject("extra");
					// jsonObject = jsonObject.getJSONObject("after_open");
					// id = jsonObject.getString("id");
					// } catch (JSONException e) {
					// // TODO Auto-generated catch block
					// e.printStackTrace();
					// }
					Intent intent = new Intent(getApplicationContext(),
							MegActivity.class);// 消息
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
				} else if (msg.activity.equals("call_message")) {// 私信消息
					DebugLog.v("bytag", "d" + msg.getRaw() + "");
					try {
						jsonObject = msg.getRaw().getJSONObject("extra");
						uid = jsonObject.getString("uid");
						nickName = jsonObject.getString("nickname");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					Intent intent = new Intent(getApplicationContext(),
							ActivitySiXinXiangQing.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra("rela_uid", uid);
					intent.putExtra("to_nick", nickName);
					startActivity(intent);

				}
			}
		};

		// 使用自定义的NotificationHandler，来结合友盟统计处理消息通知
		// 参考http://bbs.umeng.com/thread-11112-1-1.html
		// CustomNotificationHandler notificationClickHandler = new
		// CustomNotificationHandler();
		mPushAgent.setNotificationClickHandler(notificationClickHandler);

		// if (MiPushRegistar.checkDevice(this)) {
		// MiPushRegistar.register(this, "2882303761517400865",
		// "5501740053865");
		// }

	}

	public static Context getContext() {

		return context;
	}

	/**
	 * @return the queue
	 */
	public static RequestQueue getQueue() {
		return queue;
	}

	public static <T> void addRequest(Request<T> request) {
		request.addMarker("itboye");
		getQueue().add(request);
	}

}
